package com.example.yls.demoa;

import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.ShareActionProvider;

public class MainActivity extends AppCompatActivity {
  private Button btnSave;
  private Button btnRead;
  private EditText edtName;
  private EditText edtAge;
  private RadioButton radMan;
    private RadioButton radGirl;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        btnSave = findViewById(R.id.btn_save);
        btnRead = findViewById(R.id.btn_read);
        edtAge = findViewById(R.id.edt_age);
        edtName = findViewById(R.id.edt_name);
        radGirl = findViewById(R.id.rad_girl);
        radMan = findViewById(R.id.rad_man);


        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getSharedPreferences("sql", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putBoolean("isboy",true);
                editor.putString("name","su");
                editor.putInt("age",11);
                editor.commit();
            }
        });

    }
    protected void onStop() {
        String name = edtName.getText().toString();
        int age = Integer.parseInt(edtAge.getText().toString());
        boolean isBoy = radMan.isChecked();
        saveToSP(name,age,isBoy);
        super.onStop();
    }

    private void saveToSP(String name, int age, boolean isBoy) {
        SharedPreferences sharedPreferences = getSharedPreferences("person", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putBoolean("isboy",isBoy);
        editor.putString("name",name);
        editor.putInt("age",age);
        editor.commit();

    }
    protected void onResume(){
        super.onResume();
        SharedPreferences sharedPreferences = getSharedPreferences("person", Context.MODE_PRIVATE);
        boolean isBoy = sharedPreferences.getBoolean("isBoy",false);
        String name = sharedPreferences.getString("name",null);
        int age = sharedPreferences.getInt("age",0);
        edtName.setText(name);
        edtAge.setText(String.valueOf(age));
        radMan.setChecked(isBoy);
        radGirl.setChecked(!isBoy);

    }
}

